package com.work.servlet;


import com.work.dao.CarDao;
import com.work.dao.CarDaoImpl;
import com.work.dao.UserDao;
import com.work.dao.UserDaoImpl;
import com.work.pojo.Car;
import com.work.pojo.User;
import com.work.utils.MD5utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @ClassName: ${NAME}
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/20  19:30
 * 用户基本注册、登录、注销
 */
@WebServlet(name = "BasicServlet", urlPatterns = {"/register", "/login", "/logout"})
public class BasicServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String path = request.getServletPath();

        switch (path) {
            case "/register":
                register(request, response);
                break;
            case "/login":
                login(request, response);
                break;
            case "/logout":
                logout(request, response);
                break;
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    //注册
    private void register(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = new User();
        String username = request.getParameter("username");
        String userpasswords = request.getParameter("userpassword");
        String userpassword = MD5utils.code(userpasswords);
        String name = request.getParameter("name");
        String ages = request.getParameter("age");
        int age = Integer.parseInt(ages);

        user.setUser_name(username);
        user.setUser_password(userpassword);
        user.setName(name);
        user.setAge(age);

        UserDao userDao = new UserDaoImpl();
        userDao.register(user);
        response.sendRedirect("/login.jsp");
    }

    //登录
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UserDao userDao = new UserDaoImpl();
        User user = userDao.login(username, password);
        //   用户存在
        if (user != null) {
            //先判断servletContext中是否包含 用户名
            HttpSession sessionOther = (HttpSession) getServletContext().getAttribute(username);
            // 包含的话 已在其他客户端登录
            if (sessionOther != null) {
                sessionOther.removeAttribute("state");
                //已在其他客户端登录 注销其session
                sessionOther.invalidate();
            }
            HttpSession session = request.getSession();
            session.setAttribute("state", user);
            //将session放入  getServletContext    用于应对另一个客户端登录
            getServletContext().setAttribute(username, session);
            session.setAttribute("user", user);

            //获取用户未登录前的购物车信息
            HashMap<Integer, Integer> hashmap = (HashMap) request.getSession().getAttribute("hashMapGoods");
            int user_id = user.getUser_id();
            if (hashmap != null) {
                //循环加入商品到购物车
                for (Map.Entry<Integer, Integer> entry : hashmap.entrySet()) {
                    CarDao carDao = new CarDaoImpl();
                    Car car = carDao.IsRepeatGoods(entry.getKey(), user_id);
                    if (car != null) {
                        carDao.insertRepeatGoodsCar(user_id, entry.getKey(), entry.getValue()+car.getGoods_num());
                    } else {
                        carDao.insertNewGoodsCar(entry.getValue(), entry.getKey(), user_id);
                    }
                }
            }
            //   登陆成功 跳转成功页面
            request.getRequestDispatcher("/query").forward(request, response);
        } else {
            //   登陆失败 返回登录页
            response.sendRedirect("/login.jsp");
        }
    }

    //注销
    private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //获取存储在Session中的信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("state");
        //移除context中的user_name
        getServletContext().removeAttribute(user.getUser_name());
        //移除session中的state
        session.removeAttribute("state");
        //移除session
        session.invalidate();
        //返回首页
        response.sendRedirect("/query");
    }

}
